<template>
    <div class="content-page">
        <div class="content-nav">
            <el-breadcrumb class="breadcrumb" separator="/">
                <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>会员管理</el-breadcrumb-item>
                <el-breadcrumb-item>{{infoForm.id ? '编辑会员' : '新建会员'}}</el-breadcrumb-item>
            </el-breadcrumb>
            <div class="operation-nav">
                <el-button type="primary" @click="goBackPage" icon="arrow-left">返回列表</el-button>
            </div>
        </div>
        <div class="content-main">
            <div class="form-table-box">
                <el-form ref="infoForm" :rules="infoRules" :model="infoForm" label-width="120px">
                    <el-form-item label="手机号" prop="phone">
                        <el-autocomplete :trigger-on-focus="false" :fetch-suggestions="searchAsync"
                                         v-model="infoForm.phone" placeholder="请输入手机号"
                                         @select="handleSelect">
                            <template slot-scope="{item}">
                                <div>{{item.phone}}</div>
                                <span>{{item.name}}</span>
                            </template>
                        </el-autocomplete>
                    </el-form-item>
                    <el-form-item label="会员名称" prop="name">
                        <el-input v-model="infoForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="宠物名称" prop="pet_name">
                        <el-input v-model="infoForm.pet_name"></el-input>
                    </el-form-item>
                    <el-form-item label="宠物年龄" prop="pet_age">
                      <el-input v-model="infoForm.pet_age" placeholder="单位：年" @change="getBirthday"></el-input>
                    </el-form-item>
                    <el-form-item label="宠物性别" prop="pet_sex">
                        <el-select v-model="infoForm.pet_sex" placeholder="请选择免疫类型">
                            <el-option v-for="item in sexType" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="宠物类型" prop="type_path">
                        <el-cascader ref="type_path" :options="category" v-model="infoForm.type_path"
                                     change-on-select :props="props"></el-cascader>
                    </el-form-item>
                    <el-form-item label="简要描述" prop="simple_desc">
                        <el-input type="textarea" v-model="infoForm.simple_desc" :rows="3"></el-input>
                        <div class="form-tip"></div>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmitInfo">{{infoForm.id ? '更新' : '新建'}}</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>

</template>

<script>
export default {
  data () {
    return {
      // uploaderHeader: {
      //   'X-Nideshop-Token': localStorage.getItem('token') || ''
      // },
      infoForm: {
        id: 0,
        phone: '',
        name: '',
        pet_name: '',
        pet_age: '',
        pet_birthday: '',
        pet_sex: 0,
        pet_type: '',
        type_path: [0],
        simple_desc: ''
      },
      category: [
        {
          id: 0,
          name: '顶级分类'
        }
      ],
      props: {
        value: 'id',
        label: 'name',
        children: 'child'
      },
      sexType: [
        {
          id: 1,
          name: '公'
        },
        {
          id: 0,
          name: '母'
        }
      ],
      infoRules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入主人名称', trigger: 'blur' }
        ],
        pet_name: [
          { required: true, message: '请输入宠物名称', trigger: 'blur' }
        ],
        pet_age: [
          { required: true, message: '请输入宠物年龄', trigger: 'blur' }
        ],
        pet_sex: [
          { required: true, message: '请输入宠物性别', trigger: 'blur' }
        ],
        type_path: [
          { required: true, message: '请输入宠物类型', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    goBackPage () {
      this.$router.go(-1)
    },
    searchAsync (queryStr, cb) {
      this.$db.users.find({phone: new RegExp(queryStr)}, (err, docs) => {
        if (err) console.error('kumeng: ' + err.stack)
        cb(docs)
      })
    },
    handleSelect (item) {
      this.infoForm = item
    },
    getBirthday () {
      const currentDate = new Date()
      let year = currentDate.getFullYear()
      let month = currentDate.getMonth()
      if (this.infoForm.pet_age < 1) {
        this.infoForm.pet_birthday = currentDate.setMonth(month - this.infoForm.pet_age * 12)
      } else {
        this.infoForm.pet_birthday = currentDate.setFullYear(year - this.infoForm.pet_age)
      }
    },
    onSubmitInfo () {
      this.$refs['infoForm'].validate((valid) => {
        if (valid) {
          this.getBirthday()
          this.getPetType()
          this.$db.users.find({phone: this.infoForm.phone}, (err, docs) => { // find返回集合
            if (err) console.error('kumeng: ' + err.stack)
            if (docs && docs.length) {
              this.infoForm.id = docs[0].id
            } else {
              this.infoForm.id = 0
            }
            if (this.infoForm.id) {
              this.$db.users.update({id: this.infoForm.id}, this.infoForm, (err, count) => { // update 返回更新数
                if (err) console.error('kumeng: ' + err.stack)
                if (count) {
                  this.$message({
                    type: 'success',
                    message: '更新成功'
                  })
                  this.$router.go(-1)
                }
              })
            } else {
              this.$db.users.find({}).projection({id: 1}).sort({id: -1}).limit(1).exec((err, docs) => {
                if (err) console.error('kumeng: ' + err.stack)
                if (docs && docs.length) { // 获取id的最大值后加1
                  this.infoForm.id = docs[0].id + 1
                } else { // 如果是第一个数据，id=1
                  this.infoForm.id = 1
                }
                this.$db.users.insert(this.infoForm, (err, doc) => { // insert 返回插入对象
                  if (err) console.error('kumeng: ' + err.stack)
                  if (doc) {
                    this.$message({
                      type: 'success',
                      message: '新建成功'
                    })
                    this.$router.go(-1)
                  }
                })
              })
            }
          })
        } else {
          return false
        }
      })
    },
    getPetType () {
      const labels = this.$refs['type_path'].currentLabels
      this.infoForm.pet_type = ''
      for (let i = 0; i < labels.length; i++) {
        this.infoForm.pet_type += labels[i] + '/'
      }
      this.infoForm.pet_type = this.infoForm.pet_type.substring(0, this.infoForm.pet_type.length - 1)
      console.log(this.infoForm.pet_type)
    },
    async getCategory () {
      let top = await this.findCategoryWithParentId(0, 0)
      for (let i = 0; i < top.length; i++) {
        top[i].child = await this.findCategoryWithParentId(top[i].id, 1)
        if (top[i].child) {
          for (let j = 0; j < top[i].child.length; j++) {
            top[i].child[j].child = await this.findCategoryWithParentId(top[i].child[j].id, 1)
          }
        }
      }
      console.log('getCategory1: ' + JSON.stringify(top))
      this.category = this.category.concat(top)
    },
    async findCategoryWithParentId (parentId, type) {
      let query = {parent_id: parentId}
      if (type !== 0) query.type = type
      let result = await this.$db.category.asyncFind(query).then(docs => {
        if (docs && docs.length) {
          return docs
        }
      })
      return result
    },
    getInfo () {
      if (this.infoForm.id <= 0) {
        return false
      }

      // 加载用户详情
      this.$db.users.find({id: this.infoForm.id}, (err, docs) => {
        if (err) console.error('kumeng: ' + err.stack)
        if (docs && docs.length) {
          this.infoForm = docs[0]
        }
      })
    }
  },
  components: {},
  mounted () {
    this.infoForm.id = this.$route.query.id || 0
    this.getInfo()
    this.getCategory()
  },
  name: 'UserAddPage'
}
</script>

<style scoped>

</style>
